package com.xg.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.sys.entity.SysUser;
import com.xg.sys.entity.SysUserOrgEntity;
import com.xg.sys.entity.SysUserRole;
import com.xg.sys.mapper.SysUserMapper;
import com.xg.sys.mapper.SysUserRoleMapper;
import com.xg.sys.service.SysUserOrgService;
import com.xg.sys.service.SysUserRoleService;
import com.xg.sys.service.SysUserService;
import com.xg.frame.constant.SysConstant;
import com.xg.frame.entity.ConstantCode;
import com.xg.frame.exception.SqException;
import com.xg.frame.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author dehuisun
 * @since 2019-04-10
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserOrgService sysUserOrgService;

    /**
     * 用户分页查询
     *
     * @param page
     * @param userName
     */
    @Override
    public void pageList(Page<SysUser> page, String userName) {
        this.page(page,
                new LambdaQueryWrapper<SysUser>()
                        .select(
                                SysUser::getId,
                                SysUser::getUsername,
                                SysUser::getSurname,
                                SysUser::getEmail,
                                SysUser::getMobile,
                                SysUser::getStatus,
                                SysUser::getCreateUserId,
                                SysUser::getCreateTime)
                        .like(!StringUtils.isEmpty(userName), SysUser::getUsername, userName)
                        .orderByAsc(SysUser::getCreateTime)
        );
    }

    @Override
    public SysUser queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    public List<String> queryAllPerms(String userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public Set<Long> getRolesByUserId(Long userId) {

        Set<Long> roles = sysUserRoleMapper.getRolesByUserId(userId);

        return roles;
    }

    @Override
    public List<Long> selectAllMenuIds(Long id) {
        return baseMapper.selectAllMenuIds(id);
    }


    //huo
    @Override
    public SysUser selectByID(String createUser) {
        return baseMapper.selectById(createUser);
    }

    //是否首次登录
    @Override
    public boolean isFirstLogin() {
        boolean isFirst = false;
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysUser data = sysUserMapper.selectById(sysUser.getId());
        if (data != null) {
            if (SysConstant.PASSWORD.equals(data.getPassword())) {
                isFirst = true;
            }
        }
        return isFirst;
    }

    @Override
    public void removeById(Long id) throws SqException {
        try {
            super.removeById(id);
            sysUserRoleService.removeByUserId(id);
            sysUserOrgService.removeByUserId(id);
        } catch (Exception e) {
            throw new SqException(ConstantCode.NOT_DELETE.getCode(), ConstantCode.NOT_DELETE.getName());
        }
    }

    @Override
    public boolean resetPassword(Long id) {
        SysUser user = new SysUser();
        user.setId(id);
        user.setPassword(MD5Utils.stringToMD5(SysConstant.PASSWORD));
        return sysUserMapper.updateById(user) == 1;
    }

    @Override
    public List<SysUser> getByUserName(String username) {
        return super.list(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );
    }

    @Override
    public boolean removeUser(List<Long> idList) {
        final List<SysUserRole> ridListByUidList = sysUserRoleService.getRidListByUidList(idList);
        if (CollectionUtils.isNotEmpty(ridListByUidList)) {
            sysUserRoleService.removeByIds(
                    ridListByUidList.stream()
                            .map(SysUserRole::getId)
                            .collect(Collectors.toList())
            );
        }
        final List<SysUserOrgEntity> oidListByUidList = sysUserOrgService.getOidListByUidList(idList);
        if (CollectionUtils.isNotEmpty(oidListByUidList)) {
            sysUserOrgService.removeByIds(
                    oidListByUidList.stream()
                            .map(SysUserOrgEntity::getId)
                            .collect(Collectors.toList())
            );
        }
        return this.removeByIds(idList);
    }
}
